<template>
    <div class="business">
      <el-container>
        <el-header>
          <div class="hang1">
            <span> 加班申请</span>
            <el-icon color="#fb9337"><StarFilled /></el-icon>
            <el-icon color="#acb3bd"><EditPen /></el-icon>
            <el-icon color="#acb3bd"><MoreFilled /></el-icon>
          </div>
          <div class="hang2">
            <el-menu class="el-menu-demo" mode="horizontal">
              <el-row class="mb-4">
                <el-button
                  type="primary"
                  color="#fb9337"
                  class="zx"
                  @click="showDialog"
                  >发起新的</el-button
                >
                <el-upload action="/api/work/import" :headers="headers" name="excel" :data="{userid:formData.userid}" :on-change="onChange" :on-success="onSuccess" :on-error="onError" :show-file-list="false" :disabled="uploading" accept=".xlsx;.xls">
                          <el-button :loading="uploading">导入</el-button>
                </el-upload>
                <el-button>
                  <el-link :href="'/api/work/download?userid=' + formData.userid" target="_blank">导出</el-link>
                </el-button>
              </el-row>
              <el-menu-item index="1">待办事项</el-menu-item>
              <el-menu-item index="2">已办事项</el-menu-item>
              <el-menu-item index="3">抄送事项</el-menu-item>
              <el-menu-item index="4">我发起的</el-menu-item>
              <el-menu-item index="5">全部数据</el-menu-item>
              <el-menu-item index="6">概览</el-menu-item>
              <el-menu-item index="7">统计报表</el-menu-item>
            </el-menu>
          </div>
        </el-header>
        <el-main>
          <el-tabs type="border-card" class="demo-tabs">
            <el-tab-pane>
              <template #label>
                <span class="custom-tabs-label">
                  <el-icon><calendar /></el-icon>
                  <span>流程中（{{total}}）</span>
                </span>
              </template>
              <el-menu class="el-menu-demo" mode="horizontal">
                <el-menu-item index="1">
                  <el-icon><DocumentRemove /></el-icon>
                  <span>导出</span>
                </el-menu-item>
                <el-menu-item index="2">
                  <el-icon><CircleCheck /></el-icon>
                  <span>提交/通过</span>
                </el-menu-item>
                <el-menu-item index="3">
                  <el-icon><CircleClose /></el-icon>
                  <span>拒绝</span>
                </el-menu-item>
                <el-menu-item index="4">
                  <el-icon><Document /></el-icon>
                  <span>转交</span>
                </el-menu-item>
                <el-menu-item index="5">
                  <el-icon><MessageBox /></el-icon>
                  <span>打印</span>
                </el-menu-item>
                <el-menu-item index="6">
                  <el-icon><setting /></el-icon>
                  <span>字段管理</span>
                </el-menu-item>
                <el-menu-item index="7">
                  <el-icon><FullScreen /></el-icon>
                  <span>精简视图</span>
                </el-menu-item>
                <el-menu-item index="8">
                  <el-icon><Search /></el-icon>
                  <span>搜索</span>
                </el-menu-item>
              </el-menu>
              <el-table
                class="ls"
                ref="multipleTableRef"
                :data="tableData"
                style="width: 100%"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="_id" label="编号" width="100" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="status" label="当前流程" width="100" :formatter="formatterStatus"/>
                <el-table-column prop="name" label="申请人" width="100" />
                <el-table-column prop="type" label="加班类型" width="150" :formatter="dakaleixing"/>
                <el-table-column
                prop="reason"
                  label=" 加班事由说明"
                  width="200"
                />
                <el-table-column prop="starttime" label="开始时间" width="150" :formatter="formatterTime" />
                <el-table-column prop="endtime" label="结束时间" width="150" :formatter="formatterTime"/>
                <el-table-column
                prop="hours"
                  label="加班时长"
                  width="100"
                />
                <el-table-column label="操作" width="100px">
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click.prevent="editRow(scope)"
                    >
                      编辑
                    </el-button>
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click.prevent="deleteRow(scope)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
  
            <el-tab-pane>
              <template #label>
                <span class="custom-tabs-label">
                  <el-icon><calendar /></el-icon>
                  <span>待完善·0</span>
                </span>
              </template>
              待完善·0
            </el-tab-pane>
            <el-tab-pane>
              <template #label>
                <span class="custom-tabs-label">
                  <el-icon><calendar /></el-icon>
                  <span>已通过·3</span>
                </span>
              </template>
              已通过·3
            </el-tab-pane>
            <el-tab-pane>
              <template #label>
                <span class="custom-tabs-label">
                  <el-icon><calendar /></el-icon>
                  <span>已拒绝·2</span>
                </span>
              </template>
              已拒绝·2
            </el-tab-pane>
            <el-tab-pane>
              <template #label>
                <span class="custom-tabs-label">
                  <el-icon><calendar /></el-icon>
                  <span>草稿·1</span>
                </span>
              </template>
              草稿·1
            </el-tab-pane>
          </el-tabs>
          <el-pagination background class="fen"  layout="prev, pager, next" :total="total" @current-change="handleCurrentChange"/>
        </el-main>
        <!-- 抽屉 -->
        <el-drawer v-model="drawer" title="加班申请" size="50%">
         <div class="ger">个人信息</div>
          <div class="demo-drawer__content">
            <!-- 新增表单 -->
            <el-form
              :model="formData"
              label-position="top"
              :rules="rules"
              ref="formRef"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="申请人" prop="name">
                    <el-input v-model="formData.name" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所在部门">
                    <el-input v-model="formData.dept" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="加班类型" prop="type">
                    <el-select v-model="formData.type" clearable placeholder="请选择">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</el-form-item>
     
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="事由说明" prop="reason">
                    <el-input
                      type="textarea"
                      v-model="formData.reason"
                      placeholder="输入内容"
                      :autosize="{ minRows: 4, maxRows: 4 }"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="开始时间" prop="starttime">
                    <el-date-picker
                      v-model="formData.starttime"
                      type="datetime"
                      placeholder="选择一个开始时间"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束时间" prop="endtime">
                    <el-date-picker
                      v-model="formData.endtime"
                      type="datetime"
                      placeholder="选择一个结束时间"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="加班时长" prop="hours">
                    <el-input v-model="formData.hours" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
  
            <div class="demo-drawer__footer">
              <el-button type="primary" @click="xinjian(formRef)"
              >新建</el-button
              >
              <el-button @click="drawer = false">取消</el-button>
            </div>
          </div>
        </el-drawer>
      </el-container>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive,onMounted } from "vue";
  import { ElNotification } from "element-plus";
  import {work_add,work_list,work_delete} from '../../api/index'
  
  var tableData = ref([]);
  var formRef = ref();
  var total = ref(0);
  var uploading = ref(false);
  const drawer = ref(false);
  var formData = ref({
    userid: JSON.parse(localStorage.getItem("userinfo"))._id,
    name:JSON.parse(localStorage.getItem("userinfo")).name,
    reason: "",
    starttime: "",
    endtime: "",
    type: "",
    hours: "",
  });
  var headers = ref({Authorization:'Bearer' + ' ' + localStorage.getItem('token')})
  const options = [
  {
    value: '0',
    label: ' 工作日加班',
  },
  {
    value: '1',
    label: '周末加班 ',
  },
  {
    value: '2',
    label: '节假日加班 ',
  },
]
  //验证 申请人
  const validateName = (rule, value, callback) => {
      if (value === '') {
          callback(new Error('请输入申请人'))
      } else {
          callback()
      }
  }
  //验证 加班事由
  const validateReason = (rule, value, callback) => {
      if (value === '') {
          callback(new Error('请输入出差事由'))
      } else {
          callback()
      }
  }
  //验证 开始时间
  const validateStarttime = (rule, value, callback) => {
      if (value === '') {
          callback(new Error('请选择一个开始时间'))
      } else {
        if( new Date(formData.value.starttime) - new Date(formData.value.endtime) > 0 ){
              formData.value.starttime = '';
              formData.value.hours  = '';
              callback(new Error('开始时间必须早于结束时间!'))
          }else if( formData.value.starttime && formData.value.endtime  ) { 
              formData.value.hours = (new Date(formData.value.endtime) - new Date(formData.value.starttime) ) / ( 60 * 60 * 1000)
          }
          callback()
      }
  }
  //验证 返回日期
  const validateEndtime = (rule, value, callback) => {
      if (value === '') {
          callback(new Error('请选择一个开始时间'))
      } else {
        if( new Date(formData.value.starttime) - new Date(formData.value.endtime) > 0 ){
              formData.value.endtime = '';
              formData.value.hours  = '';
              callback(new Error('开始时间必须大于结束时间!'))
          }else if( formData.value.starttime && formData.value.endtime  ) { 
              formData.value.hours  = (new Date(formData.value.endtime) - new Date(formData.value.starttime) ) / (60 * 60 * 1000)
          }
         
          callback()
      }
  }
  //验证 出差总天数
  const validateHours = (rule, value, callback) => {
      if (value === '' || Number(value) == 0) {
          callback(new Error('请填写正确的总天数'))
      } else {
          callback()
      }
  }
  
  //表单的验证规则 rules
  const rules = reactive({
    name: [{ validator: validateName, trigger: 'blur',required: true, }],
    reason: [{ validator: validateReason, trigger: 'blur',required: true, }],
    starttime: [{ validator: validateStarttime, trigger: 'blur',required: true, }],
    endtime: [{ validator: validateEndtime, trigger: 'blur',required: true, }],
    hours: [{ validator: validateHours, trigger: 'blur',required: true, }],
  })
  
  //加载表单数据
  onMounted( async ()=>{
      var userinfo = JSON.parse( localStorage.getItem('userinfo') );
      var res = await work_list({ userid: userinfo._id ,page:1 })
      tableData.value = res.data.list;
      total.value = res.data.total;
  })
  //流程状态
  var formatterStatus = function(row, column, cellValue, index){
      return cellValue == 0 ? '审核中' : '已通过';
  }
  var dakaleixing = function(row, column, cellValue, index){
      return cellValue == 0 ? '工作日加班' : cellValue == 1?'周末加班':'节假日加班' ;
  }
  // 时间格式化
  var addZero = (num)=>{
      return num<10 ? '0'+num : num;
  }
  var formatterTime = function(row, column, cellValue, index){
      var d = new Date(cellValue);
      return `${d.getFullYear()}-${addZero( d.getMonth()+1 )}-${ addZero( d.getDate() ) } ${ addZero( d.getHours() ) }:${ addZero( d.getMinutes() ) }`;
  }
  // 分页
  var handleCurrentChange = async (page)=>{
      var userinfo = JSON.parse( localStorage.getItem('userinfo') );
      var res = await work_list({ userid: userinfo._id ,page })
      tableData.value = res.data.list;
  }
  // 新建数据提交
  var xinjian = (formRef) => {
    formRef.validate(async (valid) => {
      if (valid) {
        if( formData.value._id ){
           ElNotification({ 
              title: '编辑通知',
              message: '编辑成功!',
              type: 'success',
          })
           addDialog.value = false;
        }else{
        var res=await work_add(formData.value)
        if(res.data.code==200){
          ElNotification({
            title: '新增通知',
            message: res.data.msg,
            type: 'success',
          })
          drawer.value=false
          tableData.value=res.data.list
          total.value=res.data.total
          formRef.resetFields(); 
        }else{
          ElNotification({
            title: '新增通知',
            message: res.data.msg,
            type: 'error',
          })
        }
        }
      } else {
        console.log('error submit!')
        return false
      }
    })
  };
  //发起新的 出差申请
  var showDialog = ()=>{
    drawer.value = true;
      formRef.value.resetFields(); 
      formData.value = { 
          userid: JSON.parse( localStorage.getItem('userinfo') )._id,
          name: JSON.parse( localStorage.getItem('userinfo') ).name ,
          reason:'',
          starttime:'',
          endtime:'',
          type: "",
          hours: "", 
      }
      delete formData.value._id;
  }
  // 删除数据
  var deleteRow=async (scope)=>{
    var userinfo=JSON.parse(localStorage.getItem('userinfo'))
  var res=await work_delete({userid:userinfo._id,id:scope.row._id,page:1})
  if( res.data.code == 200 ){
          ElNotification({ //弹出通知
            title: '删除通知',
            message: res.data.msg,
            type: 'success',
          })
          tableData.value = res.data.list;
          total.value = res.data.total;
      }
  }
  //编辑数据
  var editRow = (scope)=>{
    drawer.value = true;
      formData.value = JSON.parse( JSON.stringify( scope.row ) );
  }
  //添加文件、上传成功和上传失败时
  var onChange = (uploadFile, uploadFiles)=>{
      if( uploadFile.percentage < 100 ){
          uploading.value = true;
      }
  }
  //文件上传成功时
  var onSuccess = async(response, uploadFile, uploadFiles)=>{
      uploading.value = false;
      if( response.code == 200 ){
          ElNotification({ 
            title: '导入通知',
            message: response.msg,
            type: 'success',
          })
          var userinfo = JSON.parse( localStorage.getItem('userinfo') );
      var res = await work_list({ userid: userinfo._id ,page:1 })
      tableData.value = res.data.list;
      total.value = res.data.total;
      }
  }
  //文件上传失败时
  var onError = (error, uploadFile, uploadFiles)=>{
      uploading.value = false;
      if( error ){
          ElNotification({ 
            title: '导入通知',
            message: '导入失败!',
            type: 'error',
          })
      }
  }
  </script>
  
  
  <style scoped lang="scss">
  .business {
    width: 100%;
    .el-header {
      padding: 0;
      height: 110px;
    }
  }
  .hang1 {
    width: 100%;
    height: 60px;
    border-bottom: 1px solid #e6eaf0;
    line-height: 60px;
    span {
      margin-left: 20px;
      font-size: 20px;
      font-weight: bold;
    }
  }
  .hang2 {
    width: 100%;
    height: 50px;
    button {
      margin-top: 14px;
      margin-left: 20px;
    }
    .zx {
      color: white;
    }
    .el-button {
      margin-right: 10px;
    }
  }
  .el-icon {
    font-size: 20px;
    margin: 0 10px;
  }
  .ls {
    text-align: left;
  }
  .ger{
    margin-bottom: 10px;
  }
  .fen{
  
    margin-top: 10px;
  }
  </style>